<template>
  <div class="container">
    <input type="file" @change="handleFileUpload" accept=".docx" />
    <div class="main-content">
      <div class="left-panel">
        <ul v-if="tableOfContents.length">
          <li v-for="(item, index) in tableOfContents" :key="index">
            <button @click="scrollToSection(item.id)">{{ item.title }}</button>
            <ul v-if="item.children && item.children.length">
              <li v-for="(child, childIndex) in item.children" :key="`${index}-${childIndex}`">
                <button @click="scrollToSection(child.id)">{{ child.title }}</button>
              </li>
            </ul>
          </li>
        </ul>
      </div>
      <div class="right-panel">
        <v-md-editor v-model="editorContent" height="500px" mode="edit-preview" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import mammoth from 'mammoth';
import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress.js';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';

VMdEditor.use(vuepressTheme);


const editorContent = ref('');
const tableOfContents = ref([]);
const sections = ref([]);

const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = async (event) => {
    const arrayBuffer = event.target.result;
    const result = await mammoth.convertToHtml({ 
      arrayBuffer,
      styleMap: [
        "p[style-name='标题 1'] => h1",
        "p[style-name='标题 2'] => h2",
        "p[style-name='标题 3'] => h3",
        "p[style-name='标题 4'] => h4",
        "p[style-name='标题 5'] => h5",
        "p[style-name='标题 6'] => h6",        
        "p => p"
      ],
      tableStyleMap: [
        "table[style-name='表格'] => table",
        "tr[style-name='表格行'] => tr",
        "td[style-name='表格单元格'] => td",
        "th[style-name='表格标题'] => th"
      ],
      imageHandler: async (image) => {
        const buffer = await image.read();
        return `<img src="data:${image.contentType};base64,${buffer.toString('base64')}">`;
      },
      tableStyleOverride: function(table) {
        return {
          className: "custom-table" // 为所有表格添加类名
        };
      }
    });
    parseDocument(result.value); // result.value包含转换后的HTML内容
  };
  reader.readAsArrayBuffer(file);
};

const parseDocument = (htmlContent) => {
  console.log('转换后的HTML内容:', htmlContent); // 添加调试日志，检查表格结构是否正确
  editorContent.value = htmlContent;
  const newSections = [];
  const toc = [];
  let currentLevel = 0;
  const stack = [toc]; // 栈初始化为根目录数组
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = htmlContent;
  const elements = tempDiv.children;

  Array.from(elements).forEach((element, index) => {
    const level = getHeadingLevel(element.tagName);
    const id = `section-${index}`;

    if (level > 0) {
      const title = element.textContent;
      const section = {
        id,
        level,
        title,
        content: '',
        children: []
      };

      // 调整栈长度匹配当前层级
      while (stack.length > level) stack.pop();
      while (stack.length < level) stack.push(stack[stack.length - 1]);
      const currentParent = stack[stack.length - 1]; // 获取当前层级的父级数组

      currentParent.push(section); // 添加到正确父级
      newSections.push(section);

      // 更新栈保存当前章节的子数组（用于下一级标题）
      if (stack.length <= level) {
        stack.push(section.children);
      } else {
        stack[level] = section.children;
      }

      currentLevel = level;
    } else {
      if (newSections.length > 0) {
        newSections[newSections.length - 1].content += element.innerHTML;
      }
    }
  });

  tableOfContents.value = toc;
  sections.value = newSections;
};

const getHeadingLevel = (tagName) => {
  if (tagName.startsWith('H') && tagName.length === 2) {
    return parseInt(tagName[1], 10);
  }
  return 0;
};

const scrollToSection = (id) => {
  const element = document.getElementById(id);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
};

const updateContent = (id, newContent) => {
  const section = sections.value.find(s => s.id === id);
  if (section) {
    section.content = newContent;
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.main-content {
  display: flex;
  margin-top: 20px;
  gap: 20px;
}

.left-panel {
  flex: 1;
  max-width: 300px;
  border-right: 1px solid #ccc;
  padding-right: 20px;
}

.right-panel {
  flex: 3;
}

button {
  background: none;
  border: none;
  text-align: left;
  cursor: pointer;
  color: #007bff;
  margin: 5px 0;
}

button:hover {
  text-decoration: underline;
}

ul {
  list-style-type: none;
  padding-left: 20px;
}
</style>

<style>
/* 全局样式确保v-html中的表格正确显示 */
.right-panel table {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}
.right-panel td, .right-panel th {
  border: 1px solid #ddd;
  padding: 8px;
}
.right-panel tr:nth-child(even) {
  background-color: #f2f2f2;
}
  .right-panel p {
    margin: 10px 0;
    line-height: 1.6;
    font-size: 16px;
  }
</style>